from argparse import ArgumentParser
import os
import sys

LOADER_SIZE = 9216
BLOCK_SIZE = 512

PL_DEV_PATH = '/dev/ttyUSB0'
AG_DEV_PATH = '/dev/ttyACM0'


def main():
    parser = ArgumentParser()
    parser.add_argument('fd', type=str)
    args = parser.parse_args()

    fd_path = os.path.abspath(args.fd)

    script_path = os.path.dirname(os.path.abspath(__file__))
    working_dir = os.path.join(script_path, '..')
    os.chdir(working_dir)
    sys.path.append(working_dir)

    import plib
    import cdalib

    assert os.path.getsize('microloader/microloader.bin') == LOADER_SIZE
    f = open('microloader/microloader.bin', 'rb')
    microloader = f.read()
    f.close()
    f = open(fd_path, 'rb')
    fd = f.read()
    f.close()

    d = plib.Device(PL_DEV_PATH, True)
    d.handshake()
    d.test()

    payload_length = len(microloader) + len(fd)
    if payload_length % BLOCK_SIZE != 0:
        padding_length = BLOCK_SIZE - (payload_length % BLOCK_SIZE)
    else:
        padding_length = 0

    d = cdalib.Device(AG_DEV_PATH, True)
    d.mmc_init(0)
    d.partition_write('boot', microloader + fd + b'\x00' * padding_length)
    d.reboot()


if __name__ == '__main__':
    main()
